function percentage_explained = zFC_VarianceDecomposition_partially(shock, variab, hor, Sigma, MovAverage_reduced, Var_struct_shocks, MovAverage_structural)

% -----------------------------------------------------%
% DESCRIPTION OF THE FUNCTION
% The function computes the variance decomposition within a partially
% identified VAR model. The decomposition is computed regarding the
% percentage that shock "shock" explains of variable "variab" at horizon
% "hor".
%
% More precisely, the model is specified in the reduced form moving average
% 
% y_t = MovAverage_reduced r_t
%     = r_t + C_1 r_t-1 + C_2 r_t-2 + ...
%
% and the variance covariance matrix of the reduced form shocks is "Sigma".
% Then the model is potentially only partially identified. Say, only the
% first column of of the "B" matrix mapping structural into reduced form
% shocks is estimated. The function computes the share of the volatility of
% all variables explained by the first shock. The other shocks are
% decompositions are computed, but they have a meaning only to the extent
% that the corresponding columns of the "B" matrix are identified. Here, if
% only the first column of "B" is identified, then the remaining columns
% are filled in randomly. Changing them will change part of the structural
% moving average representation in "MovAverage_structural" from the model 
%
% y_t = MovAverage_structural r_t
%     = D_0 s_t + D_1 s_t-1 + D_2 s_t-2 + ...
%
% but the decomposition regarding the FIRST shock will be identical. The
% same holds for the variance covariance of the structural shocks in matrix
% "Var_struct_shocks". If the model only identifies the first shock,
% changing values of the structural variances of the other shocks will not
% affect the variance decomposition related to the FIRST structural shock.
% Hence, the entire "B" and "Var_struct_shocks" do not need to be
% consistent with the reduced form representation of the model
% -----------------------------------------------------%



    k = size(Var_struct_shocks,1);

    e_vector = eye(k,k);  

    numerator   = (e_vector(:,variab)'*MovAverage_structural(:,:,1)*e_vector(:,shock))^2;
%     denominator = e_vector(:,variab)'*MovAverage_structural(:,:,1)*Var_struct_shocks*MovAverage_structural(:,:,1)'*e_vector(:,variab);
    denominator = e_vector(:,variab)'*Sigma*e_vector(:,variab);
    if hor > 1
       for h = 2:hor
          numerator   = numerator + (e_vector(:,variab)'*MovAverage_structural(:,:,h)*e_vector(:,shock))^2;
%           denominator = denominator + e_vector(:,variab)'*MovAverage_structural(:,:,h)*Var_struct_shocks*MovAverage_structural(:,:,h)'*e_vector(:,variab);
      denominator = denominator + e_vector(:,variab)'*MovAverage_reduced(:,:,h)*Sigma*MovAverage_reduced(:,:,h)'*e_vector(:,variab);
       end
    end
    numerator = numerator*Var_struct_shocks(shock,shock);
    percentage_explained = 100*numerator/denominator;


end